package net.oschina.git.hikoyan.helloapi.openoffice;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.ExternalOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

import javax.servlet.ServletContext;

public class OpenOfficeContext {

    public static final String PARAMETER_OFFICE_PORT = "office.port";
    public static final String PARAMETER_OFFICE_HOME = "office.home";
    public static final String PARAMETER_OFFICE_PROFILE = "office.profile";

    private static final String KEY = OpenOfficeContext.class.getName();

    private static OfficeManager officeManager;
    private static OfficeDocumentConverter documentConverter;

    public OpenOfficeContext(ServletContext servletContext) {
        ExternalOfficeManagerConfiguration configuration = new ExternalOfficeManagerConfiguration();
        String officePortParam = servletContext.getInitParameter(PARAMETER_OFFICE_PORT);
        if (officePortParam != null) {
            configuration.setPortNumber(Integer.parseInt(officePortParam));
        }
//        String officeHomeParam = servletContext.getInitParameter(PARAMETER_OFFICE_HOME);
//        if (officeHomeParam != null) {
//            configuration.setOfficeHome(new File(officeHomeParam));
//        }
//        String officeProfileParam = servletContext.getInitParameter(PARAMETER_OFFICE_PROFILE);
//        if (officeProfileParam != null) {
//            configuration.setTemplateProfileDir(new File(officeProfileParam)); //
//        }

        officeManager = configuration.buildOfficeManager();
        documentConverter = new OfficeDocumentConverter(officeManager);
    }

    protected static void init(ServletContext servletContext) {
        OpenOfficeContext instance = new OpenOfficeContext(servletContext);
        instance.officeManager.start();
    }

    protected static void destroy(ServletContext servletContext) {
        OpenOfficeContext instance = get(servletContext);
        instance.officeManager.stop();
    }

    public static OpenOfficeContext get(ServletContext servletContext) {
        return (OpenOfficeContext) servletContext.getAttribute(KEY);
    }

    public static OfficeManager getOfficeManager() {
        return officeManager;
    }

    public static OfficeDocumentConverter getDocumentConverter() {
        return documentConverter;
    }
}
